
#include "CScreenManager.h"

#include "screens/CScreen.h"

CScreenManager::CScreenManager()
{
    initialized = false;
}

CScreenManager::~CScreenManager()
{

}

void CScreenManager::init( CGraphics *gl )
{
    this->gl = gl;
    initialized = true;
}

void CScreenManager::addSound( CAudioManager *am )
{
    this->am = am;
}

CAudioManager* CScreenManager::getSound()
{
    return this->am;
}

int CScreenManager::update( CInput *in )
{
    for ( int i = 0; i < add.size(); i++ ) {
        screens.append( add[i] );
    }
    add.clear();

    for ( int i = 0; i < remove.size(); i++ ) {
//        remove[i]->unload( gl );
//        screens.removeOne( remove[i] );
        delete remove[i];
    }
    remove.clear();

    if ( screens.size() > 0 )
        return screens.last()->update( in );
    else
        return -1;
}

void CScreenManager::draw( CGraphics *gl )
{
    if ( add.size() == 0 && screens.size() != 0 )
        screens.last()->setHidden( false );

    for ( int i = 0; i < screens.size(); i++ ) {
        if ( !screens[i]->isHidden() )
            screens[i]->draw( gl );
    }
    // Ekranų debuginimo tikslais. vėliau ištrinti
//    glColor3f( 1.0f, 1.0f, 1.0f );
//    gl->renderTexts( 10, 20, QString("Screens:"), QFont("Verdana", 10, 0, 0 ) );
//    int i = 35;
//    foreach ( CScreen *sc, screens ) {
//        gl->renderTexts( 10, i, sc->getName()+ " " + ((sc->isHidden())?"hidden":"visible"), QFont("Verdana", 10, 0, 0 ) );
//        i+= 15;
//    }

}

void CScreenManager::addScreen( CScreen *sc )
{
    add.append( sc );
    sc->setScreenManager( this );
    sc->load( gl );
//    screens.append( sc );
}

void CScreenManager::removeScreen( CScreen *screen )
{
    foreach ( CScreen *sc, screens ) {
        if ( sc == screen ) {
            remove.append( sc );
            sc->unload( gl );
            screens.removeOne( sc );
//            delete sc;
            break;
        }
    }
}

void CScreenManager::removeScreen( QString name )
{
    foreach ( CScreen *sc, screens ) {
        if ( sc->getName() == name ) {
            remove.append(sc);
            sc->unload( gl );
            screens.removeOne( sc );
//            delete sc;
            break;
        }
    }
}

CScreen* CScreenManager::getScreen( QString name )
{
    foreach ( CScreen *sc, screens ) {
        if ( sc->getName() == name )
            return sc;
    }
    return 0;
}
